<!-- 物流线路 - 表单编辑页面 -->
<template>
  <div class="page_base">

    <el-form ref="formEl" :model="formValue" :rules="rules" label-width="120px"
      class="common-form-panel-div flex_auto scroll_auto">

      <ex_header_spiler :title="$t('label_pms_product_base_info')"></ex_header_spiler>
      <el-row style="margin-top: 20px;">
        <el-col>
          <!--产品名称  -->
          <el-form-item :label="$t('label_pms_product_name')">
            <el-input v-model="formValue.productName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <!-- 产品编码 -->
          <el-form-item :label="$t('label_pms_product_code')">
            <el-input v-model="formValue.productCode" :disabled="isEditModel"></el-input>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row style="margin-top: 20px;">
        <el-col>
          <el-form-item :label="$t('label_remark')">
            <el-input v-model="formValue.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <!-- 走货属性 -->
          <el-form-item :label="$t('label_transport_goods')">
            <transport_goods_select v-model="formValue.cargoPropertyCode" @changeItem="cargoPropertyChange"
              class="w_fill"></transport_goods_select>

          </el-form-item>
        </el-col>
      </el-row>
      <!-- 业务类型 -->
      <!-- <el-row>
        <el-col>
          <el-form-item :label="$t('label_business_type')">
            <el-input v-model="formValue.productCode" :disabled="isEditModel"></el-input>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row>
        <el-col :span="3">
          <!-- 产品类别 -->
          <el-form-item :label="$t('label_pms_product_type')">
            <el-radio-group v-model="formValue.productType" @change="productTypeChange" :disabled="isEditModel">
              <el-radio-button label="FIRST_TRANSPORT">{{ $t('PmsProductTypeEnum__FIRST_TRANSPORT')
                }}</el-radio-button>
              <el-radio-button label="LAST_TRANSPORT">{{ $t('PmsProductTypeEnum__LAST_TRANSPORT') }}</el-radio-button>
              <el-radio-button label="EXPRESS">{{ $t('PmsProductTypeEnum__EXPRESS') }}</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="2"> 
          <!-- 关联线路 -->
          <el-form-item :label="$t('label_pms_ref_line_info')">
            <el-select v-model="formValue.lineStartEnd" :placeholder="$t('tip_please_select')" filterable  style="width: 100%;">
              <!--  :disabled="isEditModel" -->
              <el-option v-for="item in lineArray" :key="item.startPlaceId + '_' + item.endPlaceId"
                :label="`${item.lineName} 【${item.startPlaceName} -> ${item.endPlaceName}】`"
                :value="item.startPlaceId + '_' + item.endPlaceId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 物流分区配置 -->
        <el-col>
          <el-form-item label="" label-width="10px">
            <el-button @click="$refs.transportAreaOrigin.show(formValue.areaLimitConfigList)"
              style="margin-top: 1px;">{{
      $t('label_logistics_division_config') }}
            </el-button>
            <transport-area-edit ref="transportAreaOrigin" :areaIds="formValue.endAreaIds"
              :countryCode="formValue.endCountryCode" :countryName="formValue.endCountryName" sourceType="product"
              @afterSubmitSuccess="areaEdit"></transport-area-edit>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="3">

          <!-- 路由过滤 -->
          <el-form-item :label="$t('label_pms_transport_route_filter')">

            <div style="display: flex;" class="product-line-limit-div">
              <!-- 干线运输方式 -->
              <div class="product-line-limit-col" style="width: 200px; margin-right: 12px;">
                {{ $t('label_pms_main_transport_type') }}</div>
              <!-- 重量限制范围 -->
              <div class="product-line-limit-col">{{ $t('label_pms_weight_range') }} kg</div>
              <!-- 体积限制范围 -->
              <div class="product-line-limit-col">{{ $t('label_pms_volume_range') }} cbm</div>
              <!-- 最长边限制 -->
              <div class="product-line-limit-col" style="width: 140px;">{{ $t('label_pms_max_lengh') }} cm</div>
              <!--              -->
              <div class="product-line-limit-col" style="width: 140px;"> {{ $t('label_pms_max_edge_length') }} cm</div>
            </div>
            <div style="display: flex; line-height: 48px; " class="product-line-limit-div">
              <ex_super_input v-model="formValue.pmsTransportRule.mainType" type="select"
                enum="LogisticsProductsTypeEnum" style="width: 200px; margin-right: 12px; " clearable></ex_super_input>

              <div class="product-line-limit-col" style=" display: flex;">
                <el-input placeholder="0kg" v-model="formValue.pmsTransportRule.minWeight" clearable></el-input>
                <div style="padding: 0px 4px;">{{ $t('label_link') }}</div>
                <el-input placeholder="99999kg" v-model="formValue.pmsTransportRule.maxWeight" clearable></el-input>
              </div>

              <div class="product-line-limit-col" style=" display: flex;">
                <el-input placeholder="0 cbm" v-model="formValue.pmsTransportRule.minVolume" clearable></el-input>
                <div style="padding: 0px 4px;">{{ $t('label_link') }}</div>
                <el-input placeholder="99999 cbm" v-model="formValue.pmsTransportRule.maxVolume" clearable></el-input>
              </div>
              <div class="product-line-limit-col" style="width: 140px;">
                <el-input v-model="formValue.pmsTransportRule.maxBorder" clearable></el-input>
              </div>
              <div class="product-line-limit-col" style="width: 140px;">
                <el-input v-model="formValue.pmsTransportRule.maxEdgeLength" clearable></el-input>
              </div>
              <div class="product-line-limit-col" style="width: 80px;">
                <el-button @click="refreshRouteOption()">{{ $t('label_filter') }}</el-button>
              </div>
            </div>

          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="3">
          <!-- 路由关联 -->
          <el-form-item :label="$t('label_pms_transport_route_ref')">
            <el-radio-group v-model="formValue.lineConfigurationRule" @change="refreshRouteOption">
              <el-radio label="AUTO">{{ $t('label_pms_transport_automatch') }}</el-radio>
              <el-radio label="MANUAL">{{ $t('label_pms_transport_artificialmatch') }}</el-radio>
            </el-radio-group>


            <ex_super_table ref="autoRouteTableRef" v-if="formValue.lineConfigurationRule === 'AUTO'"
              v-bind="autoOption" :data="routeArray" @selection-change="e => selection = e" />

            <div v-else>
              <div style="text-align: right;margin-bottom: 10px;">
                <el-button @click="routerAdd" size="mini" type="primary">
                  {{ $tt('label_base_add') }}
                </el-button>
              </div>
              <ex_super_table v-bind="manualOption" :data="formValue.tmsRoutes" />
            </div>

          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <!-- 路由命中策略 -->
          <el-form-item :label="$t('label_pms_match_rules')">
            <ex_super_input v-model="formValue.matchPriority" type="select" enum="PmsTransportMatchPriorityEnum"
              style="width: 100%;"></ex_super_input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <!-- 运输时效 -->
          <el-form-item :label="$t('label_pms_prescription')">
            <el-input v-model="formValue.prescription">
              <template slot="append">{{ $t('label_pms_hour') }}</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="formValue.productType == 'LAST_TRANSPORT'">
        <el-col :span="3">
          <!-- 打包方式 -->
          <el-form-item :label="$t('label_pms_package_type')">
            <div style="display: flex; align-items: center; ">
              <el-radio-group v-model="formValue.packageType">
                <el-radio-button label="ONE_TICKET_ONE_PIECE">{{ $t('DistributionTypeEnum__ONE_TICKET_ONE_PIECE')
                  }}</el-radio-button>
                <el-radio-button label="ONE_TICKET_MANY_PIECE">{{ $t('DistributionTypeEnum__ONE_TICKET_MANY_PIECE')
                  }}</el-radio-button>
              </el-radio-group>

              <span style="color:#666; padding-left: 30px;" v-if="formValue.packageType == 'ONE_TICKET_ONE_PIECE'">
                <!-- 一个 sku 或多个 sku 打成一个包裹，生成一张面单 -->
                <i class="el-icon-warning" style="margin-right: 8px;"></i>{{ $t('label_pms_ONE_TICKET_ONE_PIECE')
                }}</span>
              <span style="color:#666; padding-left: 30px;" v-if="formValue.packageType == 'ONE_TICKET_MANY_PIECE'">
                <!-- 按件或按箱将 sku 打成多个包裹，生成多张面单 -->
                <i class="el-icon-warning" style="margin-right: 8px;"></i>{{ $t('label_pms_ONE_TICKET_MANY_PIECE')
                }}</span>
              <span style="color:#666; padding-left: 30px;" v-if="formValue.packageType == 'ONE_TICKET_MANY_BOX'">
                <!-- 单个托盘打成一个大包裹，一个托盘贴一张面单  -->
                <i class="el-icon-warning" style="margin-right: 8px;"></i>{{ $t('label_pms_ONE_TICKET_MANY_BOX')
                }}</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="2">
          <el-form-item :label="$t('报价方式')">

            <div style="display: flex; align-items: center; ">
              <el-radio-group v-model="formValue.priceModel"> <!-- :disabled="isEditModel" -->
                <!-- 线上报价 -->
                <el-radio-button label="ONLINE">{{ $t('CustomerOrderPriceModelEnum__ONLINE') }}</el-radio-button>
                <!-- 线下询价 -->
                <el-radio-button label="OFFLINE">{{ $t('CustomerOrderPriceModelEnum__OFFLINE') }}</el-radio-button>
              </el-radio-group>

              <span style="color:#666; padding-left: 30px;" v-if="formValue.priceModel == 'OFFLINE'">
                <i class="el-icon-warning" style="margin-right: 8px;"></i>{{ $t('tip_pms_product5') }}
              </span>

            </div>
          </el-form-item>
        </el-col>

      </el-row>

      <template>

        <!-- 关联信息 -->
        <ex_header_spiler :title="$t('label_pms_ref_form_info')"></ex_header_spiler>
        <el-row style="margin-top: 20px;" v-if="formValue.productType == 'FIRST_TRANSPORT'">

          <!-- 始发中转仓库 -->
          <el-col>
            <el-form-item :label="$t('label_pms_start_warehouse')">
              <pms-warehouse-select v-model="formValue.startPlaceWarehouse" style="width: 100%;"></pms-warehouse-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="isNeedWarehouse">
          <el-col>
            <!-- 目的存储仓库 -->
            <el-form-item :label="$t('label_pms_dest_warehouse')">
              <pms-warehouse-select v-model="formValue.endPlaceWarehouse" style="width: 100%;"></pms-warehouse-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <!-- 保险服务 -->
            <el-form-item :label="$t('label_pms_insurance_service')">
              <!-- 开启物流保险服务 -->
              <el-checkbox v-model="formValue.supportInsurance" true-label="Y" false-label="N">{{
      $t('label_pms_open_insurance_service') }}</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="formValue.supportInsurance == 'Y'">
          <el-col>
            <!-- 保险产品 -->
            <el-form-item :label="$t('label_pms_insurance_product')">
              <!-- 请选择保险产品 -->
              <el-select v-model="formValue.insuranceProductId" :placeholder="$t('label_pms_please_choose_insurance')"
                style="width: 100%;" clearable>
                <el-option v-for="item in insuranceProductArr" :key="item.id" :label="item.productName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!-- 物流标准费用配置 -->
      <ex_header_spiler :title="$t('label_pms_transport_standard_cfg')" style="margin-top: 10px;"></ex_header_spiler>

      <el-row v-if="formValue.priceModel == 'OFFLINE'">
        <el-col>
          <!-- 结算币种 -->
          <el-form-item :label="$t('label_pms_product_currency')">
            <fms-currency-choose v-model="formValue.currencyType" style="width:100%;"></fms-currency-choose>
          </el-form-item>
        </el-col>
      </el-row>
      <div style="position: relative;" class="static-col-3" v-if="formValue.priceModel == 'ONLINE'">

        <!-- 添加价卡版本 -->
        <el-button @click="adTabConfig" style="position: absolute;  top: 0px; right: 20px; z-index: 999; "
          icon="el-icon-plus">{{ $t('label_pms_add_price_card_version') }}</el-button>

        <!--  v-if=" activeName != getTabId(formValue.standardPriceVersions[0]) " -->
        <ex-button-delete style="position: absolute;  top: 60px; left: 420px; z-index: 999; "
          v-if="formValue.standardPriceVersions && formValue.standardPriceVersions.length > 0 && activeName != getTabId(formValue.standardPriceVersions[0])"
          :message="$t('tip_pms_price_card_1')" :label="$t('tip_pms_price_card_2')" byAction :delAction="() => {
      formValue.standardPriceVersions = formValue.standardPriceVersions.filter(tab => getTabId(tab) != activeName);
      activeName = getTabId(formValue.standardPriceVersions[0]);
    }"></ex-button-delete>

        <el-tabs v-if="formValue.standardPriceVersions && formValue.standardPriceVersions.length > 0"
          v-model="activeName" type="card">
          <el-tab-pane v-for="(item, index) in formValue.standardPriceVersions" :label="getTabTitle(item)"
            :name="getTabId(item)" :key="item.id">
            <transport-price-cfg ref="transportPriceCfg" :priceVersionId="item.id"
              :versionStartTimeDisabled="index == 0" :inputValue="item" showCostPoint
              :productType="formValue.productType" @dateRangeChange="val => {
      item.versionStartTime = val[0];
      item.versionEndTime = val[1];
    }"></transport-price-cfg>
          </el-tab-pane>
        </el-tabs>

        <div v-else style="padding-left: 100px; display: flex; align-items: center;  color: #d41515; ">
          <i class="el-icon-warning" style="margin-right: 8px;"></i>
          {{ $t('tip_pms_price_card_3') }}
        </div>

      </div>


    </el-form>
    <div class="page_base_bottom_button" style="padding-left: 140px; ">
      <el-button type="primary" @click="submitForm()">{{ $t('label_save') }}</el-button>
      <el-button @click="goback()">{{ $t('label_cancel') }}</el-button>
    </div>

  </div>
</template>
<script>
import TransportPriceCfg from '@/component/pms/transport_price_cfg.vue'

import TransportAreaEdit from '@/component/pms/transport-area-edit.vue'

import FmsCurrencyChoose from '@/component/fms/fms-currency-choose.vue'

import PmsPricePoint from '@/component/pms/pms-price-point.vue'

import PmsWarehouseSelect from '@/component/pms/pms-warehouse-select.vue'

import PmsRouteFilterSelect from '@/component/pms/pms-route-filter-select.vue'

export default {

  components: { TransportPriceCfg, TransportAreaEdit, FmsCurrencyChoose, PmsPricePoint, PmsWarehouseSelect, PmsRouteFilterSelect },
  mixins: [],
  data() {

    return {

      selection: [],
      "operateType": "",
      "activeName": "",
      "formValue": {
        remark:"",
        routeIds: [],
        tmsRoutes: [],
        lineConfigurationRule: 'AUTO',
        cargoPropertyId: '',
        cargoPropertyCode: '',
        cargoPropertyName: '',
        "packageType": "ONE_TICKET_ONE_PIECE",
        "transportMainPrice": {},
        "matchPriority": "PRICE_FIRST",
        "productCode": "",
        "productName": "",
        "priceModel": "ONLINE",
        "lineStartEnd": "",
        "productType": "FIRST_TRANSPORT",
        "prescription": 72,
        "pmsTransportRule": {},
        "autoRemoveInvalid": true,
        "startPlaceWarehouseProductId": "",
        "endPlaceWarehouseProductId": "",
        "insuranceProductId": "",
        "supportInsurance": "N",
        "standardPriceVersions": [],
        endAreaIds: [],
        // 物流分区 尺寸限制
        areaLimitConfigList: [
          // {
          //   "areaId": "",
          //   "areaCode": "",
          //   "areaName": "",
          //   "minWeight": null,
          //   "maxWeight": null,
          //   "minVolume": null,
          //   "maxVolume": null,
          //   "maxBorder": null,
          //   "maxEdgeLength": null
          // }
        ],
      },

      "additionalCost": [
        { 'costName': '燃油费', costType: 'order', price: '200' },
        { 'costName': '报关费', costType: 'skuNum', price: '100' },
      ],

      "lineArray": [],
      "lineCache": {},

      "routeArray": [],
      "chargeTypeMap": {},



      // 关联产品
      "insuranceProductArr": [],
      "warehouseProductArr": [],
      "warehouseProductMap": {},

      "transportProductStatusMap": {
        "FIRST_TRANSPORT": [],
        "LAST_TRANSPORT": []
      },

      "loadSuccessNum": 0,
      "serviceCostArr": [],
      "trarnsportStatusPointArray": [],

      "isEditModel": false,
      supplierList: [],
      autoOption: {
        showIndex: false,
        model: [
          { type: 'selection', clickToggle: true },
          { key: 'supplyName', label: 'label_pms_transport_supply' },
          { key: 'lineName', label: 'label_pms_line_route', formatter: (r, c, v, i) => r.ownerType == 'THIRD' ? r.lineName : r.lineName + ' - ' + r.routeName },
          { key: 'supplyName', label: 'label_srm_supplier_type', formatter: (r, c, v, i) => r.ownerType == 'THIRD' ? this.$t('label_pms_third') : this.$t('label_pms_own') },
          { key: 'lineCode', label: 'label_srm_transport_line_code' }
        ]
      },
      manualOption: {
        showIndex: false,
        model: [
          {
            key: 'supplyId',
            label: 'label_pms_transport_supply',
            "label-class-name": "label_require_before",
            width: 300,
            render: (h, { column, row, index }) => {
              const prop = `tmsRoutes.${index}.${column.property}`
              const rule = this.rules[column.property]
              return (
                <el-form-item prop={prop} rules={rule}>
                  <ex_super_input
                    value={row.supplyId}
                    type="select"
                    onChange={(e) => {
                      this.$set(row, 'supplyId', e)
                      this.$set(row, 'lineId', '')
                    }}
                    items={this.supplierList}
                    option={{ label: 'supplierName', value: 'id' }} />
                </el-form-item>
              )
            }
          },
          {
            key: 'lineId',
            label: 'label_pms_line_route',
            "label-class-name": "label_require_before",
            width: 300,
            render: (h, { column, row, index }) => {
              const prop = `tmsRoutes.${index}.${column.property}`
              const rule = this.rules[column.property]
              return (
                <el-form-item prop={prop} rules={rule}>
                  <ex_super_input
                    value={row.lineId}
                    type="select"
                    onChangeItem={(e) => {
                      this.$set(row, 'lineId', e.lineId)
                      Object.keys(this.routeInit).forEach(key => {
                        this.$set(row, key, e[key])
                      })
                    }}
                    url='/fms-api/product/PmsTransportRouteRuleRpc/queryRoute.json'
                    dependentId={row.supplyId}
                    urlControl={this.urlControlFun}
                    urlParams={{ supplyId: row.supplyId }}
                    option={{ label: 'lineName', value: 'lineId' }} />
                </el-form-item>
              )
            }
          },
          { key: 'supplyName', label: 'label_srm_supplier_type', formatter: (r, c, v, i) => r.ownerType == 'THIRD' ? this.$t('label_pms_third') : this.$t('label_pms_own') },
          { key: 'lineCode', label: 'label_srm_transport_line_code' },
          {
            type: 'operate', width: 170, operate: [
              {
                label: "label_remove",
                class: "button_text_danger",
                disabled: () => this.formValue.tmsRoutes.length === 1,
                click: (row, i) => this.routerRemove(i)
              },
            ]
          }
        ]
      },
      routeInit: {
        id: '',
        supplyProductId: '',
        routeId: '',
        supplyId: '',
        supplyName: '',
        lineId: '',
        lineCode: '',
        lineName: '',
        routeName: '',
        ownerType: 'THIRD'
      },
      rules: {
        supplyId: [{ required: true, message: this.$t('tip_can_no_empty'), trigger: 'blur' }],
        lineId: [{ required: true, message: this.$t('tip_can_no_empty'), trigger: 'blur' }],
      }
    };
  },

  created() {

    let _this = this

    let editId = this.$route.query.id;

    if (editId) {
      // 修改物流产品
      this.$tag.tagModifyLabel(_this.$t('label_modify') + _this.$t('label_logistics'))
      this.isEditModel = true
    } else {
      // 新增物流产品
      this.$tag.tagModifyLabel(_this.$t('label_new') + _this.$t('label_logistics'))
    }

    // 加载线路
    _this.$ajax({
      url: '/fms-api/product/PmsTransportRouteRuleRpc/queryLine.json',
      success: (res) => {
        if (res && res.data && res.data.rows) {
          _this.lineArray = res.data.rows;
          _this.lineArray.forEach(e => {
            _this.lineCache[e.startPlaceId + '_' + e.endPlaceId] = e
          })
        }

        _this.loadSuccessNum = _this.loadSuccessNum + 1
        _this.initFormPanel()
      }
    });

    // 获取单位相关映射
    _this.$ajax({
      url: '/fms-api/product/PriceUnitRpc/getPriceUnitMap.json',
      success: (res) => {
        if (res && res.data) {
          _this.chargeTypeMap = res.data
        }
        _this.loadSuccessNum = _this.loadSuccessNum + 1
        _this.initFormPanel()
      }
    });

    // 保险产品
    _this.$ajax({
      url: '/fms-api/product/PmsInsuranceProductRpc/selectSimple.json',
      success: (res) => {
        if (res && res.data && res.data.rows) {
          _this.insuranceProductArr = res.data.rows
        }
        _this.loadSuccessNum = _this.loadSuccessNum + 1
        _this.initFormPanel()
      }
    });

    // 仓储产品
    _this.$ajax({
      url: '/fms-api/product/PmsWarehouseProductRpc/selectPage.json',
      success: (res) => {
        if (res && res.data && res.data.rows) {

          let v = res.data.rows

          let warehouseProductArr = []
          let warehouseProductMap = {}
          v.forEach(group => {
            let tmpArr = []
            if (group.warehouseGroups && group.warehouseGroups.length > 0) {
              group.warehouseGroups.forEach(whs => {
                whs.warehouses.forEach(wh => tmpArr.push(wh.warehouseName))
              })
            }
            warehouseProductMap[group.id] = tmpArr.join(', ')
            warehouseProductArr.push({
              'id': group.id,
              'productName': group.productName,
            })
          })

          _this.warehouseProductArr = warehouseProductArr
          _this.warehouseProductMap = warehouseProductMap
        }
        _this.loadSuccessNum = _this.loadSuccessNum + 1
        _this.initFormPanel()
      }
    });


    // 更新场景 加载表单
    if (editId) {

      _this.$ajax({
        url: '/fms-api/product/PmsTransportProductRpc/detail.json?id=' + editId,
        success: (res) => {
          if (res && res.data) {
            _this.formValueCache = res.data
          }

          _this.loadSuccessNum = _this.loadSuccessNum + 1
          _this.initFormPanel()
        }
      });

    } else {

      // window.setTimeout(()=>{
      //   _this.$refs['transportPriceEl'].updateForm()
      // }, 300)

      // let lastTime = new Date().getTime()
      let tmpObj = this.getDefaultObj()

      this.formValue.standardPriceVersions.push(tmpObj)
      this.activeName = this.getTabId(tmpObj)

    }


    // 获取可选费用项
    _this.$ajax({
      url: '/fms-api/agent/AgentServiceCostRpc/selectEnable.json',
      success: (res) => {
        if (res && res.data && res.data.rows) {
          _this.serviceCostArr = res.data.rows
        }
      }
    });


  },

  mounted() {
  },

  watch: {

    'formValue.formValue.pmsTransportRule'(val, old) {
    },

    'formValue.productType'(val, old) {

      if (val == '' || !val || !this.transportProductStatusMap[val]) {
        this.trarnsportStatusPointArray = []
        return
      }
      this.trarnsportStatusPointArray = this.transportProductStatusMap[val]
    },

    'formValue.lineStartEnd'(val, old) {
      this.refreshRouteOption()
    }
  },

  computed: {
    isNeedWarehouse: function () {

      let j = this.formValue.productType === 'FIRST_TRANSPORT' || this.formValue.productType === 'LAST_TRANSPORT'

      return j
    }


  },

  methods: {

    dateTimeRangeChange(val) {
      // val => { item.versionStartTime=val[0]; item.versionEndTime=val[1]; }
      // console.log(val)
    },

    getDefaultObj(areaList) {

      let lastTime = new Date().getTime()

      let tmpObj = {
        "id": 'id_' + (Math.random() + '').replace('.', ''),
        "daterange": [lastTime, parseInt(lastTime) + 31536000000],
        "versionId": "-1",
        "versionName": "",
        "versionStartTime": lastTime,
        "versionEndTime": parseInt(lastTime) + 31536000000,
        "priceVersionTime": "1688471661285",
        "versionType": "CUSTOMER",
        "transportMainPrice":
        {
          "chargeType": "WEIGHT",
          "priceType": "MULTI_ADD",
          "calWeightRate": 6000,
          "priceConfigs": [],
          "pricePoint": "",
          "currencyType": "CNY"
        },
        "additionPrices": [],
        "customers": [],
        "productId": "",
        "versionTag": "",
        "status": "ENABLE"
      }

      if (areaList && areaList.length > 0) {
        areaList.forEach(area => {
          tmpObj.transportMainPrice.priceConfigs.push({
            areaId: area.id,
            areaCode: area.code,
            areaName: area.name,
            pricePeriod: [{ start: 0, end: 1, price: 10, startPrice: 10, addPrice: 10 }, { start: 1, end: 10, price: 10, startPrice: 10, addPrice: 10 }, { start: 10, end: 50, price: 10, startPrice: 10, addPrice: 10 }],
            singlePrice: 100
          })
        })
      }

      return tmpObj
    },

    adTabConfig() {

      let sample = null

      if (this.formValue.standardPriceVersions && this.formValue.standardPriceVersions.length > 0) {
        sample = JSON.parse(JSON.stringify(this.formValue.standardPriceVersions[this.formValue.standardPriceVersions.length - 1]))
        let lastTime = sample.versionEndTime
        sample.versionStartTime = parseInt(lastTime) + 86400000
        sample.versionEndTime = parseInt(lastTime) + 31536000000
        sample.id = 'id_' + Math.random()
      }
      else {


        let list = this.$refs['transportAreaOrigin'].getSelection()
        if (!list || list.length == 0) {
          this.$message({
            type: 'error',
            message: this.$t('tip_pms_product6')
          })
          return
        }

        let whArr = list.map(it => {
          return {
            id: it.id,
            name: it.subareaName,
          }
        })

        // console.log(whArr)

        sample = this.getDefaultObj(whArr)

      }

      this.formValue.standardPriceVersions.push(sample)
      this.activeName = this.getTabId(sample)

    },

    getTabTitle(item) {
      return this.$dateFormatDate(item.versionStartTime) + this.$t('label_link') + this.$dateFormatDate(item.versionEndTime)
    },

    getTabId(item) {
      return 'tab_' + item.id
    },

    getCurrentIndex() {
      let index = parseInt(this.activeName.substring(9))
      // console.log('remove index: ' + index)
      return index
    },
    productTypeChange(){
      this.formValue.tmsRoutes=[]
      this.refreshRouteOption()
    },
    refreshRouteOption() {

      let tmps = []
      if (this.formValue.lineStartEnd) {
        tmps = this.formValue.lineStartEnd.split('_')
        let line = this.lineCache[this.formValue.lineStartEnd]
        if (line) {
          this.formValue.startPlaceId = line.startPlaceId
          this.formValue.startPlaceName = line.startPlaceName
          this.formValue.endPlaceId = line.endPlaceId
          this.formValue.endPlaceName = line.endPlaceName
          this.formValue.endPlaceName = line.endPlaceName
          this.formValue.endCountryCode = line.endCountryCode
          this.formValue.endCountryName = line.endCountryName
        }
      }

      // 自动匹配 如果没有关联线路 内容清空
      if (this.formValue.lineConfigurationRule === 'AUTO' && !this.formValue.lineStartEnd) {
        this.routeArray = []
        this.autoCheckRoute()
        return
      }

      if (this.formValue.lineConfigurationRule === 'MANUAL') {
        this.getSupplierList()
      } else {
        this.autoRoute({
          startPlaceId: tmps[0],
          endPlaceId: tmps[1],
        })
      }
    },
    // 获取所有服务商 用来查询服务商对应的线路
    getSupplierList() {
      let supplierType = ''
      switch (this.formValue.productType) {
        case 'FIRST_TRANSPORT':
          supplierType = 'FIRST_SUPPLIER'
          break;
        case 'LAST_TRANSPORT':
          supplierType = 'LAST_SUPPLIER'
          break;
      }
      this.$ajax({
        url: '/srm-api/supplier/SupplierRpc/selectPage.json',
        data: {
          supplierType,
          pageIndex: 1,
          pageSize: 999
        },
        success: (res) => {
          if (res && res.data && res.data.rows) {
            this.supplierList = res.data.rows
          }
        }
      });

    },
    // 线路自动匹配 获取相关路由
    autoRoute(params) {
      this.$ajax({
        url: '/fms-api/product/PmsTransportRouteRuleRpc/queryRoute.json',
        data: {
          ...params,
          ...this.formValue.pmsTransportRule
        },
        success: (res) => {
          if (res && res.data && res.data.rows) {
            this.routeArray = res.data.rows
            this.autoCheckRoute()
          }
        }
      });
    },
    // 必要接口加载完后 初始化
    initFormPanel() {

      let _this = this
      let editId = this.$route.query.id;

      if (editId) {
        if (_this.loadSuccessNum >= 5) {

          if (_this.formValueCache.standardPriceVersions && _this.formValueCache.standardPriceVersions.length > 0) {
            _this.activeName = _this.getTabId(_this.formValueCache.standardPriceVersions[0])

            _this.formValueCache.standardPriceVersions.forEach(r => {
              r.labelTitle = _this.getTabTitle(r)
            })

          }

          for (let kk in _this.formValueCache) {
            _this.formValue[kk] = _this.formValueCache[kk]
          }

          _this.formValue.lineStartEnd = _this.formValue.startPlaceId + '_' + _this.formValue.endPlaceId
          _this.formValue.routeIds = _this.formValue.tmsRoutes.map(e => e.routeId)



          _this.autoCheckRoute()

        }
      }
    },
    autoCheckRoute() {
      this.$nextTick(() => {
        this.routeArray.forEach(item => {
          if (this.formValue.routeIds.includes(item.routeId)) {
            this.$refs['autoRouteTableRef'].toggleRowSelection(item, true)
          }
        })
      })
    },
    updateArea(list) {
      let whArr = list.map(it => {
        return {
          id: it.id,
          areaCode: it.groupCode,
          name: it.subareaName,
          countryCode: it.countryCode
        }
      })
      if (!this.$refs['transportPriceCfg']) {
        return
      }
      this.$refs['transportPriceCfg'].forEach(e => {
        e.updateArea(whArr)
      })
    },

    submitForm() {


      this.$refs['formEl'].validate((valid) => {
        if (valid) {
          let submitData = JSON.parse(JSON.stringify(this.formValue))

          // 路由关联 自动时 值为勾选内容
          // 手动时 过滤重复线路 服务商id+线路id
          if (this.formValue.lineConfigurationRule === 'AUTO') {
            submitData.tmsRoutes = this.selection
          } else {
            submitData.tmsRoutes = submitData.tmsRoutes.filter((currentValue, currentIndex, selfArr) => {
              return selfArr.findIndex(x => (x.supplyId + x.lineId) === (currentValue.supplyId + currentValue.lineId)) === currentIndex
            })
          }

          // 物流报价
          if (this.formValue.standardPriceVersions && this.formValue.standardPriceVersions.length > 0) {
            let standardPriceVersions = this.$refs['transportPriceCfg'].map(e => e.getFormData())

            this.formValue.standardPriceVersions = standardPriceVersions

          }
          this.$ajax({
            url: '/fms-api/product/PmsTransportProductRpc/saveUpdate.json',
            type: 'json',
            data: submitData,
            success: (responseData) => {

              this.$message({
                showClose: true,
                message: this.$t('tip_submit_success'),  //'提交成功',
                type: 'success'
              })
              this.$tag.tagClose()

            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });


    },

    goback() {
      this.$tag.tagClose()
    },
    // 物流分区配置 确定后处理数据
    areaEdit(list) {
      this.formValue.endAreaIds = list.map(it => it.id)
      this.updateArea(list)
      this.formValue.areaLimitConfigList = list.map(item => {
        item.areaId = item.id
        return item
      })
    },
    cargoPropertyChange(item) {
      this.$set(this.formValue, 'cargoPropertyId', item.id)
      this.$set(this.formValue, 'cargoPropertyCode', item.code)
      this.$set(this.formValue, 'cargoPropertyName', item.name)
    },
    routerAdd() {
      this.formValue.tmsRoutes.push(JSON.parse(JSON.stringify(this.routeInit)))
    },
    routerRemove(index) {
      this.formValue.tmsRoutes.splice(index, 1)
    },
    urlControlFun(params) {
      if (params.supplyId) {
        return true
      } else {
        return {
          netStop: true,
          focusInnerData: [],
        }
      }
    },
  }
};

</script>
<style>
.product-line-limit-div,
.product-line-limit-div-2 {
  display: flex;
}


.product-line-limit-div .product-line-limit-col {
  width: 220px;
  text-align: center;
  margin-right: 10px;
}

.product-line-limit-div-2 div {
  width: 300px;
  /*text-align: center;*/
  margin-right: 10px;
}

.price-cal-div-row {
  display: flex;
}

.price-cal-div-row .price-cal-col {
  width: 120px;
  text-align: center;
}

.price-cal-div-row div {
  margin-right: 8px;
  text-align: center;
}
</style>
